﻿using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using WYJ.Log.LogWriters;

namespace WYJ.Log.LogServices
{
    /// <summary>
    /// 每个级别一个通道。
    /// </summary>
    public class MultiPassageLogger : BaseLogger, ILogger
    {
        public static ILogger Use(Func<LogLevel, ILogWriter> setWriter, LogLevel logLevel = LogLevel.INFO) => new MultiPassageLogger(setWriter, logLevel);
        public static ILogger GetLogToFileSevice(string file, LogLevel logLevel = LogLevel.INFO)
        {
            OTFWriter writer = new OTFWriter(file);
            return Use(level => new OTOWriter(writer), logLevel);
        }


        private readonly Dictionary<LogLevel, ILogWriter> _loggers;

        private MultiPassageLogger(Func<LogLevel, ILogWriter> setWriter, LogLevel logLevel)
        {
            _loggers = Levels.Where(level => level >= logLevel).ToDictionary(level => level, level => setWriter(level));
        }



        public void PauseAll()
        {
            foreach (var item in _loggers.Keys)
            {
                Pause(item);
            }
        }

        public void ResumeAll()
        {
            foreach (var item in _loggers.Keys)
            {
                Resume(item);
            }
        }

        public void Dispose()
        {
            foreach (var logger in _loggers.Values) { logger.Dispose(); }
            _loggers.Clear();
            Thread.Sleep(1000);
            GC.SuppressFinalize(this);
        }

        protected override ILogWriter? GetLogger(LogLevel logLevel)
        {
            return _loggers.GetValueOrDefault(logLevel);
        }
    }
}